//创建用户相关的小仓库
import {defineStore} from 'pinia';
//引入接口
import { reqLogin,reqUserInfo,reqLogout} from '../../api/user';


import type { loginFormData,loginResponseData,userInfoResponseData } from '@/api/user/type';
import type { UserState } from './types/type';


//引入操作本地存储的工具方法
import { SET_TOKEN,GET_TOKEN,REMOVE_TOKEN } from '../../utils/token';
//引入路由（常量）
import { constantRoute ,asnycRoute,anyRoute} from '../../router/routes';
//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router';

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute:any,routes:any){
    return asnycRoute.filter((item:any)=>{
        if(routes.includes(item.name)){
            if(item.children&&item.children.length>0){
                item.children=filterAsyncRoute(item.children,routes);
            }
            return true;
        }
    })
}



//创建用户小仓库
let useUserStore=defineStore('User',{
    //存储数据
    state: ():UserState=>{
        return {
            token: GET_TOKEN(),
            menuRoutes:constantRoute,//仓库存储生成菜单需要数组
            username: '',
            avatar: '',
            //存储当前用户是否包含按钮
            buttons:[],
        }
    },
    //处理异步|逻辑的地方
    actions:{
        //用户登录的方法
        async userLogin(data:loginFormData){
           let result:loginResponseData=await reqLogin(data);
           console.log('用户登录');
           console.log(result);
           //登录成功200，获取到token
            if(result.code==200){
                this.token=(result.data as string);
                //本地存储持久化存储一份
                SET_TOKEN(result.data as string);
                return 'ok';
            }

           //失败201，返回登录失败的错误信息
           else{
                return Promise.reject(new Error(result.message));
           }
        },
        async userInfo(){
            //获取用户的信息进行存储
            let request:userInfoResponseData =await reqUserInfo();
            console.log('获取用户信息');
            console.log(request);
            if(request.code==200){
                this.username=request.data.name;
                this.avatar=request.data.avatar;
                this.buttons=request.data.buttons;
                //计算当前用户需要展示的异步路由
                let userAsyncRoute=filterAsyncRoute(cloneDeep(asnycRoute),request.data.routes);
                this.menuRoutes=[...constantRoute,...userAsyncRoute,anyRoute];
                //异步路由动态追加
                [...userAsyncRoute,anyRoute].forEach((route:any)=>{
                   router.addRoute(route)
                })
                return 'ok';
            }
            else{
                return Promise.reject(request.message);
            }
        },

        //退出登录
        async userLogout(){
            let result= await reqLogout();
            console.log('退出登录');
            console.log(result);
            if(result.code==200){
                
                this.token='';
                this.username='';
                this.avatar='';
                REMOVE_TOKEN();
                return 'ok';
            }
            else{
                return Promise.reject(new Error(result.message));
            }
            
        }



    },
    getters:{

    }

})
//对外暴露获取小仓库的方法
export default useUserStore;